#ifndef __UPGRADE_H
#define __UPGRADE_H

#include "stdint.h"

typedef enum{
    MCU_NOT_UPGRADE_STATUS = 0U,
    MCU_START_UPGRADE_STATUS,
    MCU_UPGRADE_IN_PROGRESS,
    MCU_UPGRADE_FAIL_STATUS,
    MCU_UPGRADE_DONE_STATUS,
}MCU_UpgradeStatus;



#define   PACKET_HEADER_SIZE        (12)
#define   PACKET_DATA_SIZE          (512)
#define   PACKET_TOTAL_SIZE         (PACKET_HEADER_SIZE + PACKET_DATA_SIZE)

/* LYNX */
#define   PACKET_MAGIC_NUM               (0x4C594E58)

#define   MCU_SEND_ACK                   ((uint8_t)0x5A)
#define   MCU_SEND_UPGRADE_SUCCESS_ACK   ((uint8_t)0x5B)
#define   MCU_WRITE_FLASH_ERROR          ((uint8_t)0xFA)
#define   MCU_VERIFY_PACKET_ERROR        ((uint8_t)0xF0)

#define   MCU_SEND_PACKET_MAX_ERROR_COUNT   10

/* do not exceed half of flash size */
#define   PACKET_TOTAL_MAX_NUM      (64)

/* MCU send ack 100ms timeout */
#define   MCU_SEND_ACK_TIMEOUT       (100)

typedef struct mcu_upgrade_packet_header
{
	uint32_t magic_num;
	uint8_t  total_packet_num;
	uint8_t  serial_num;
	uint16_t  length;
	uint32_t crc32;
}UpgradePacketHeader;

typedef enum{
	MCU_UPGRADE_PACKET_VERIFY_OK = 0U,
	MCU_UPGRADE_PACKET_SIZE_ERROR,
	MCU_UPGRADE_PACKET_MAGIC_ERROR,
	MCU_UPGRADE_PACKET_TOTAL_NUM_ERROR,
	MCU_UPGRADE_PACKET_CRC_ERROR
}UpgradeStatus;


extern uint32_t g_upgrade_status;


void upgrade_firmware(void);
uint8_t mcu_upgrade_packet(uint8_t *data, uint16_t len);
void wait_for_upgrade(void);
void set_upgrase_status(uint8_t status);
uint8_t get_upgrade_status(void);
void mcu_begin_upgrade();
#endif
